package top.ranzhang.controller.other;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.ranzhang.bean.dto.EmailOtherDTO;
import top.ranzhang.bean.dto.LoginOtherDTO;
import top.ranzhang.bean.dto.RegisterOtherDTO;
import top.ranzhang.bean.vo.OtherLoginVO;
import top.ranzhang.common.result.Result;
import top.ranzhang.service.OtherService;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 特殊用户模块
 */

@Slf4j
@RestController
@RequestMapping("/register")
@RequiredArgsConstructor
public class RegisterController {

    private final OtherService otherService;

    private final RedisTemplate redisTemplate;
    /**
     * 上传图片
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/saveImage")
    public Result<String> SaveImage(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        log.info("文件名：{}",fileName);
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + extension;
        File saveFile = new File("C:\\image\\" + newFileName);
        if(saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        file.transferTo(saveFile);
        return Result.success(saveFile.getAbsolutePath(),"上传成功");
    }

    /**
     * 注册
     * @param registerOtherDTO
     * @return
     */
    @PostMapping("/addOther")
    public Result registerOther(RegisterOtherDTO registerOtherDTO){
        otherService.save(registerOtherDTO);
        return Result.success("注册成功");
    }

    /**
     * 登录
     * @param loginOtherDTO
     * @return
     */
    @PostMapping("/loginRedis")
    public Result loginRedis(LoginOtherDTO loginOtherDTO){
        OtherLoginVO otherLoginVO = otherService.loginRedis(loginOtherDTO);
        redisTemplate.opsForValue().set("token:" + otherLoginVO.getUsername(),otherLoginVO,  4*60*60, TimeUnit.MINUTES);
        return Result.success(otherLoginVO,"登录成功");
    }

    /**
     * 邮箱登录
     */
    @PostMapping("/loginEmail")
    public Result loginEmail(@RequestBody EmailOtherDTO loginOtherDTO){
        OtherLoginVO otherLoginVO = otherService.loginEmail(loginOtherDTO);
        return Result.success(otherLoginVO,"登录成功");
    }

    /**
     * 获取邮箱登录验证码
     */
    @GetMapping("/getEmailCode")
    public Result getEmailCode(String email){
        otherService.getEmailCode(email);
        return Result.success();
    }

}
